///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.data {
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	import sugarcookie.collections.EnhancedArrayCollection;
	import sugarcookie.data.handlers.IDataHandler;
	import sugarcookie.error.ApplicationError;
	import sugarcookie.events.DataEvent;
	
	public class DataChannels extends EventDispatcher implements IEventDispatcher {
		protected var _log:ILogger;
		
		protected var _dataRepository:EnhancedArrayCollection;
		protected var _lastChannelAdded:String;
		
		public function DataChannels() {
			super();
			_log = Log.getLogger("sugarcookie.data.DataChannels");
			_dataRepository = new EnhancedArrayCollection();
		}
		
		public function get lastChannelAdded():String {
			return _lastChannelAdded;
		}
		
		final protected function addDataChannel(id:String, dc:IDataHandler):void {
			//check for id
			if (!isChannelAvailable(id)) {
				throw new ApplicationError("Channel ID already exists. Channel was not added.");
				return;
			}
			
			_log.debug("Adding channel: "+id);
			_lastChannelAdded = id;
			
			//add event listeners
			if (id!="config") {
				dc.addEventListener(DataEvent.ON_DATA_CHANNEL_RETURN,onDataChannelReturn,false,0,true);
				dc.addEventListener(DataEvent.ON_DATA_CHANNEL_ERROR,onDataChannelError,false,0,true);
			}
			
			dc.init();
			
			_dataRepository.addItemWithKey(id,dc);
		}
	
		final protected function getDataChannel(id:String):* {
			//check for id
			if (isChannelAvailable(id)) throw new ApplicationError("Channel ID does not exist.");
			return IDataHandler(_dataRepository.getItemAtKey(id));
		}
		
	
		final protected function isChannelAvailable(id:String):Boolean {
			return !_dataRepository.containsKey(id);
		}
		
		final protected function removeDataChannel(id:String):void {
			//check for id
			if (isChannelAvailable(id)) {
				throw new ApplicationError("Channel ID does not exist.  No channel was removed.");
				return;
			}
			
			_dataRepository.getItemAtKey(id).kill();
			_dataRepository.removeItemAtKey(id);
		}
		
		protected function onDataChannelReturn(evt:DataEvent):void {
			//to be overridden in subclass
			_log.debug("DataManager.onDataChannelReturn() - implement your own custom handlers for the default IDataChannel Events");
		}
		
		protected function onDataChannelError(evt:DataEvent):void {
			//to be overridden in subclass
			_log.debug("DataManager.onDataChannelError() - implement your own custom handlers for the default IDataChannel Events");
		}
	}
}